package com.apes.fn.fico.reimbursement.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.fico.reimbursement.model.ExpenseDebitItem;
import com.apes.fn.fico.reimbursement.model.FeeType;
import com.apes.fn.fico.reimbursement.model.ReimbursementTypeItem;
import com.apes.fn.fico.reimbursement.repository.*;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.jpa.spec.model.Group;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.AccessProvider;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.AccessProviderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 费用类型
 * Created by lishikun on 2021/1/27 18:51
 */
@Service("feeTypeService")
public class FeeTypeService extends DomainService {
    @Autowired
    FeeTypeRepository feeTypeRepository;

    @Autowired
    ExpenseDebitItemRepository expenseDebitItemRepository;

    @Autowired
    ReimbursementTypeItemRepository reimbursementTypeItemRepository;

    @Autowired
    AccessProviderRepository accessProviderRepository;

    public FeeType create(SimpleRequest request) {
        FeeType feeType = request.getO(FeeType.class);
        if (feeType.getWithholdingSubjectMark() == null) feeType.setWithholdingSubjectMark(false);
        if (feeType.getPendingSubjectMark() == null) feeType.setPendingSubjectMark(false);
        if (feeType.getReimbursementMark() == null) feeType.setReimbursementMark(false);
        if (feeType.getAccessProvider() == null) throw new RuntimeException("请检查本角色公司是否配置接入商");
        return feeTypeRepository.saveAndFlush(feeType);
    }

    public FeeType update(SimpleRequest request) {
        FeeType feeType = request.getO(FeeType.class);
        return feeTypeRepository.saveAndFlush(feeType);
    }

    public String delete(SimpleRequest request) {
        FeeType feeType = feeTypeRepository.findOne(request.get("id").toString());
        List<ReimbursementTypeItem> reimbursementTypeItems = reimbursementTypeItemRepository.findAll(JpaDsl.toCriteriaByEq("feeType", feeType));
        List<ExpenseDebitItem> expenseDebitItems = expenseDebitItemRepository.findAll(JpaDsl.toCriteriaByEq("feeType", feeType));

        if (reimbursementTypeItems.size() > 0 || expenseDebitItems != null && expenseDebitItems.size() > 0)
            throw new RuntimeException("已使用的费用类型，不允许删除。");
            feeTypeRepository.delete(feeType);

        return "删除成功";
    }

    public AccessProvider findAccessProvider(SimpleRequest request){
        PartyRole company = request.getCurrentCompany();
        return accessProviderRepository.findByCompany(company.getId());
    }

    public Page<FeeType> findAllByAccessProvider(SimpleRequest request){
        PartyRole company = request.getCurrentCompany();
        List<FeeType> feeTypeList;
        JSONObject jsonObject = request.getJO();
        Map<String, Object> map = new HashMap<>();
        if(jsonObject.containsKey("key") && !"".equals(jsonObject.get("key"))) {
            map.put("id",jsonObject.get("key"));
            map.put("name",jsonObject.get("key"));
        }
        if(jsonObject.containsKey("condition")){
            if(JSONArray.parseArray(jsonObject.get("condition").toString()).size() != 0){
                List<Map> listMaps = MapUtil.mapped(JSONArray.parseArray(jsonObject.get("condition").toString()));
                map.put("id","null");
                map.put("name","null");
                listMaps.forEach(maps -> map.put(maps.get("field").toString(),maps.get("value")));
            } else {
                feeTypeList = feeTypeRepository.findAll(new Sort(Sort.Direction.ASC, "id"));
                feeTypeList = feeTypeList.stream().filter(feeType -> feeType.getAccessProvider() != null).filter(feeType -> {
                    List<PartyRole> companys = feeType.getAccessProvider().getCompanys();
                    return companys.contains(company);
                }).collect(Collectors.toList());
                return (Page<FeeType>) paged(feeTypeList, request.get("page"), request.get("size"), null);
            }
        }
        if(jsonObject.containsKey("group")){
            Group group = MapUtil.getO(JSONObject.parseObject(jsonObject.get("group").toString()), Group.class);
            feeTypeList = feeTypeRepository.findAll(JpaDsl.build(group,false),new Sort(Sort.Direction.ASC, "id"));
            feeTypeList = feeTypeList.stream().filter(feeType -> feeType.getAccessProvider() != null).filter(feeType -> {
                List<PartyRole> companys = feeType.getAccessProvider().getCompanys();
                return companys.contains(company);
            }).collect(Collectors.toList());
            return (Page<FeeType>) paged(feeTypeList, request.get("page"), request.get("size"), null);
        }
        if(map.isEmpty()) {
            feeTypeList = feeTypeRepository.findAll(JpaDsl.toCriteria("valid", "EQ", 1),new Sort(Sort.Direction.ASC, "id"));
        } else {
            feeTypeList = feeTypeRepository.findByFilterMapAndReimbursementMark(map.get("id").toString(),map.get("name").toString());
        }
        if(!feeTypeList.isEmpty()) {
            feeTypeList = feeTypeList.stream().filter(feeType -> feeType.getAccessProvider() != null).filter(feeType -> {
                List<PartyRole> companys = feeType.getAccessProvider().getCompanys();
                return companys.contains(company);
            }).collect(Collectors.toList());
        }
        return (Page<FeeType>) paged(feeTypeList, request.get("page"), request.get("size"), null);
    }
}
